package fcgi

import (
	"fmt"
	"net/http"

	fcgi "github.com/tomasen/fcgi_client"
)

// FCGIClient FastCGI客户端封装
type FCGIClient struct {
	client *fcgi.FCGIClient
	addr   string
}

// NewFCGIClient 创建新的FastCGI客户端
func NewFCGIClient(addr string) (*FCGIClient, error) {
	client, err := fcgi.Dial("tcp", addr)
	if err != nil {
		return nil, fmt.Errorf("connect to FastCGI server failed: %v", err)
	}

	return &FCGIClient{
		client: client,
		addr:   addr,
	}, nil
}

// Process 处理FastCGI请求
func (c *FCGIClient) Process(r *http.Request) (*http.Response, error) {
	env := make(map[string]string)
	env["REQUEST_METHOD"] = r.Method
	env["SCRIPT_FILENAME"] = r.URL.Path
	env["QUERY_STRING"] = r.URL.RawQuery
	env["SERVER_PROTOCOL"] = r.Proto
	env["REMOTE_ADDR"] = r.RemoteAddr
	env["REQUEST_URI"] = r.RequestURI

	resp, err := c.client.Request(env, r.Body)
	if err != nil {
		return nil, fmt.Errorf("FastCGI request failed: %v", err)
	}

	return resp, nil
}

// Close 关闭FastCGI连接
func (c *FCGIClient) Close() error {
	if c.client != nil {
		c.client.Close()
	}
	return nil
}
